﻿using GalaSoft.MvvmLight;
using System.Linq;
using System.Xml.Linq;
using System.Net;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using wp7cinema.Model;
using GalaSoft.MvvmLight.Command;
using wp7cinema.ExtendedMethod;
using Microsoft.Phone.Controls;

namespace wp7cinema.ViewModel
{
    public class MovieListViewModel : ViewModelBase
    {
        private List<IEnumerable<MovieSimpleInfo>> _movieSetList;
        public List<IEnumerable<MovieSimpleInfo>> MovieSetList
        {
            get { return _movieSetList; }
            set
            {
                _movieSetList = value;
                RaisePropertyChanged("MovieSetList");
            }
        }

        #region 바인딩될 데이터
        private IEnumerable<MovieSimpleInfo> _movieSet;
        public IEnumerable<MovieSimpleInfo> MovieSet
        {
            get { return _movieSet; }
            set
            {
                _movieSet = value;
                RaisePropertyChanged("MovieSet");
            }
        }
        #endregion

        #region Command 들...

        public RelayCommand<Int32> ChangeMovieSetCommand { get; set; }
        public void ChangeMovieSetCommandExecute(Int32 param)
        {
            //int index = Convert.ToInt32(param);
            int index = param;
            if (_movieSetList == null) return;
            MovieSet = _movieSetList[index];
        }
        public RelayCommand<MovieSimpleInfo> SetMovieInfoCommand { get; set; }
        public void SetMovieInfoCommandExecute(MovieSimpleInfo info)
        {
            if (info == null) return;
            info.SetResource("MovieSimpleInfo");

            //PhoneApplicationFrame frame = App.Current.RootVisual as PhoneApplicationFrame;
            //frame.Navigate(new Uri("/View/MovieDetailView.xaml", UriKind.Relative));
            //if (info == null) return;

            //if (App.Current.Resources["MovieSimpleInfo"] != null)
            //    App.Current.Resources.Remove("MovieSimpleInfo");

            //App.Current.Resources.Add("MovieSimpleInfo", info);
        }
        #endregion

        #region 생성자

        public MovieListViewModel()
        {
            if (IsInDesignMode)
            {
                #region 디자인용 더미데이터
                ObservableCollection<MovieSimpleInfo> m = new ObservableCollection<MovieSimpleInfo>();
                for (int i = 0; i < 10; i++)
                {
                    m.Add(new MovieSimpleInfo
                    {
                        ImgUrl = "http://imgmovie.naver.com/mdi/mit500/0664/66463_P46_190114.jpg",
                        Title = "토이스토리 " + i,
                        Point = (9.82 - i).ToString(),
                        ShareRate = "34",
                        ReleaseDay = "12월09일",
                        Rank = i+1
                    });
                }
                MovieSet = m;
                MovieSetList = new List<IEnumerable<MovieSimpleInfo>>();
                for (int i = 0; i < 4; i++)
                {
                    MovieSetList.Add(m);
                }
                #endregion
            }
            else
            {
                xmlDownload();

                ChangeMovieSetCommand = new RelayCommand<Int32>(ChangeMovieSetCommandExecute);
                SetMovieInfoCommand = new RelayCommand<MovieSimpleInfo>(SetMovieInfoCommandExecute);
            }
        }
        #endregion

        #region 영화목록 다운로드

        private void xmlDownload()
        {
            string url = "http://movie.naver.com/mainflash.xml";
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(url));
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string xml = e.Result;
            xml = xml.Replace("&lt", "").Replace("&gt", "");
            XDocument xdoc = XDocument.Parse(xml);

            int rank = 1;
            MovieSetList = xdoc.Descendants("movieSet")
                .Select(movieSet => {
                    return movieSet.Descendants("movie").Select(movie =>
                    {
                        string[] releaseDay = movie.Attribute("releaseDay").Value.Split('.');
                        if (rank > 10) rank = rank % 10;
                        return new MovieSimpleInfo
                        {
                            ImgUrl = movie.Attribute("imgurl").Value,
                            Description = movie.Attribute("description").Value,
                            DetailViewCode = movie.Attribute("detailViewCode").Value,
                            Genre = movie.Attribute("genre").Value,
                            Point = movie.Attribute("point").Value,
                            PreorderCode = movie.Attribute("preorderCode").Value,
                            ReleaseDay = releaseDay[1] + "월" + releaseDay[2] + "일",
                            Runtime = movie.Attribute("runtime").Value,
                            ShareRate = movie.Attribute("shareRate").Value,
                            Title = movie.Attribute("title").Value,
                            Rank = rank++
                        };
                    });
                }).ToList<IEnumerable<MovieSimpleInfo>>();

            foreach (IEnumerable<MovieSimpleInfo> movies in MovieSetList)
            {
                rank = 1;
                foreach (MovieSimpleInfo movie in movies)
                {
                    movie.Rank = rank++;
                }
            }
            //MovieSet = movieSetList[0];
        }
        #endregion

        ////public override void Cleanup()
        ////{
        ////    // Clean own resources if needed

        ////    base.Cleanup();
        ////}
    }
}